<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查看用药</title>
    <link rel="stylesheet" href="../../../layui/css/layui.css" media="all">
    <script src="../../../js/jquery/1.x/jquery.js"></script>
    <script src="../../../layui/layui.js" charset="utf-8"></script>
    <script src="../../../js/config.js"></script>
    <script src="../../../js/function.js"></script>
    <link rel="stylesheet" href="../../../css/public.css">
    <link rel="stylesheet" href="../../../css/patient/qss.css">
    <style>
        .js-dosageBox{position:absolute;left:10px;top:30px;width:140px;height:120px;border:1px solid #ccc;
            border-radius:3px;background:#fff;padding:5px;z-index:998;text-align:left;line-height:24px;}
        .js-dosage{width:40px;}
        .js-remarkBox{position:absolute;left:10px;top:30px;padding:5px;background-color:#fff;z-index:998;display:none;}
        .js-date{width:80px;}
        .js-dose{width:60px;}
        a{color:#4777E7}
        a:hover{color:#4777E7}
    </style>
</head>
<body>
<div class="fixed-form">
    <form class="layui-form">
        <div class="qss-item" style="padding:0;">
            <div class="qss-item-title">
                <p>药物调整记录：</p>
            </div>
            <div class="qss-form-item layui-form-item">
                <div class="qss-item-table">
                    <table class="layui-table" lay-even lay-skin="" style="border:1px solid #cccccc;">
                        <thead>
                        <tr>
                            <th style="width:8%;">序号</th>
                            <th style="width:8%;">变更</th>
                            <th style="width:8%;">开始时间</th>
                            <th style="width:8%;">调整时间</th>
                            <th style="width:8%;">结束时间</th>
                            <th style="width:8%;">单位</th>
                            <th style="width:8%;">每日总剂量</th>
                            <th style="width:8%;">注射次数</th>
                            <th style="width:8%;">用法用量</th>
                            <th style="width:8%;">备注</th>
                            <th style="width:8%;">操作人</th>
                        </tr>
                        </thead>
                        <tbody id="drugList">

                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="fixed-form-item-confirm">
            <div class="editBox hide">
                <button type="button"  class="cancel-btn" id="btnCancel">取消</button>
                <button type="button" style="background:#4777E7;color:white;" id="btnSubmit">提交</button>
            </div>
            <button type="button"  class="cancel-btn" id="btnEdit">编辑</button>

        </div>
    </form>
</div>




</body>
<script>
    var modeId = getQueryString('mode_id'); //1 垂体用药 2降糖 3降压 4 其它用药
    var drugId = getQueryString('id'); //1 垂体用药 2降糖 3降压 4 其它用药
    var patient_id = getLocalStorage('patient_id');
    var postRecords = {};
    //济量调整的str
    function  getDosageStr(val1,val2,val3,val4,val5,val6) {
        if(val1 == 0) val1 = '';
        if(val2 == 0) val2 = '';
        if(val3 == 0) val3 = '';
        if(val4 == 0) val4 = '';
        if(val5 == 0) val5 = '';
        if(val6 == 0) val6 = '';
        str = '<div class="js-dosageBox hide">' +
            '早: <input type="text" lay-verify="drug_dose" lay-verType="tips" class="js-dosage js-dosage1" value="'+ val1 +'" readonly/> <br/>' +
            '中: <input type="text" lay-verify="drug_dose" lay-verType="tips" class="js-dosage js-dosage2" value="'+ val2 +'" readonly/> <br/>' +
            '晚: <input type="text" lay-verify="drug_dose" lay-verType="tips" class="js-dosage js-dosage3" value="'+ val3 +'" readonly/> <br/>' +
            '睡前: <input type="text" lay-verify="drug_dose" lay-verType="tips" class="js-dosage js-dosage4" value="'+ val4 +'" readonly/> <br/>' +
            '其它: <input type="text" lay-verify="other_mock" lay-verType="tips" class="js-dosage js-dosage5" value="'+ val5 +'" readonly/>&nbsp;<input type="text" lay-verify="other_dose" lay-verType="tips" class="js-dosage js-dosage6" value="'+ val6 +'" readonly/>' +
            '</div>';
        return str;
    }
    function getDrugList(id,form) {
        ajax_get(configUrl.host + '/api/v1/pituitary/drug_records/'+ id,{id:id},function(res){
            console.log(res);
            if(res.status != 0){
                alert(res.msg);
                return false;
            }
            data = res.data;
            var drugType = {1:'新增',2:'调整',3:'停药',4:'重新开始'}
            //用量

            $.each(res.data.list,function(index,item){
                startDate = item.start_date == '0001-01-01' ? '' : '<input class="startDate js-date" readonly value="'+ item.start_date +'" />';
                endDate = item.end_date == '0001-01-01' ? '' : '<input class="endDate js-date" readonly value="'+ item.end_date +'" />';
                adjustDate = item.adjust_date == '0001-01-01' ? '' : '<input class="adjustDate js-date" readonly value="'+ item.adjust_date +'" />';
                remark = item.remark == '' ? '' : '<span title="'+ item.remark +'">备注</span>';
                
                otherText = '';
                otherMock = 0;
                if(item.usage_dosage_other.text) otherText = item.usage_dosage_other.text;
                if(item.usage_dosage_other.mock) otherMock = item.usage_dosage_other.mock;
                console.log('other=',otherText + '-'+ otherMock);
                dosageStr = getDosageStr(
                    item.usage_dosage_morning, //早
                    item.usage_dosage_noon, //中
                    item.usage_dosage_night, //晚
                    item.usage_dosage_bedtime, //睡前
                    otherText,
                    otherMock
                );
                drugTimes = item.drug_times == 0 ? '-' : item.drug_times;
                var remarkStr = '<div class="js-remarkBox"><input type="text" class="js-remark" lay-verify="remark_text" lay-verType="tips" value="'+ item.remark +'" readonly/></div>';
                var str = '<tr data-id="'+ item.id +'" data-pdid="'+ item.pituitary_drugs_id +'" data-rrid="'+ item.relation_records_id +'"' +
                    ' data-drug_type="'+ item.drug_type +'">' +
                    '<td>'+ (index+1) +'</td><td id="dStatus">'+ drugType[item.drug_type] +'</td>' +
                    '<td>'+ startDate +'</td>'+
                    '<td>'+ adjustDate +'</td><td class="endTime">'+ endDate +'</td>'+
                    '<td><div class="js-unit"> '+ item.unit + '</div>'+
                    '</td><td><input class="layui-input-inline js-dose"  style="width:60px;" type="text" lay-verify="drug_dose" lay-verType="tips" value="'+ item.drug_dose +'" readonly /></td>'+
                    '<td>'+ drugTimes +'</td><td><a href="javascript:;" class="js-list-dosage">详情</a>'+ dosageStr +'</td>'+
                    '<td><a href="javascript:;" class="js-list-remark">'+ remark +'</a>'+ remarkStr +'</td>'+
                    '<td id="optName">'+ item.doc_name +'</td></tr>';
                postRecords[item.id] = item;
                $("#drugList").append(str);
            });
            pageIndex = parent.layui.layer.getFrameIndex(window.name); //获取窗口索引
            top.layer.iframeAuto(pageIndex,30);
        })

    }
    //调为编辑状态
    function changeToEdit(form,laydate){
        //日期
        $("#drugList .js-date").each(function(){
            console.log($(this).html());
            var oVal = $(this).html();
            var tmpId = 'date-'+ Math.ceil(Math.random()*100);
            str1 = '<input type="text" value="'+ oVal +'" id="'+ tmpId +'"/>';
            $(this).html(str1);
            laydate.render({
                trigger:'click',
                elem:this
            });
            $(this).attr('readonly',false);
        });
        //单位
        $("#drugList .js-unit").each(function(index,item){
            oVal2 = $(this).html().replace(' ','');
            str2 = '<select class="" name="unit'+ index+'">' +
                '<option value="ug"'+ (oVal2 == 'ug' ? ' selected' : '') +'>ug</option>\n' +
                '<option value="g"'+ (oVal2 == 'g' ? ' selected' : '') +'>g</option>\n' +
                '<option value="U"'+ (oVal2 == 'U' ? ' selected' : '') +'>U</option>\n' +
                '<option value="ml"'+ (oVal2 == 'ml' ? ' selected' : '') +'>ml</option>\n' +
                '<option value="粒"'+ (oVal2 == '粒' ? ' selected' : '') +'>粒</option>\n' +
                '<option value="袋"'+ (oVal2 == '袋' ? ' selected' : '') +'>袋</option>\n' +
                '<option value="片"'+ (oVal2 == '片' ? ' selected' : '') +'>片</option>' +
                '<option value="支"'+ (oVal2 == '支' ? ' selected' : '') +'>支</option></select>';
            $(this).html(str2);
            console.log('v2=',oVal2);
            //$("#drugList input[name='unit"+index+"']").val(oVal2);
        })
        //济量
        $("#drugList .js-dose").each(function(){
            $(this).attr('readonly',false);
        });
        $("#drugList .js-dosage").attr('readonly',false);
        $("#drugList .js-remark").attr('readonly',false);
        form.render();
    }
    $(document).ready(function () {
        var height = $(window).height() - 2;
        //$('.container').height(height);
        if(top.location != self.location){
            pageIndex = parent.layui.layer.getFrameIndex(window.name); //获取窗口索引
        }else{
            pageIndex = 0;
        }

        layui.use(['element', 'form', 'layer', 'laydate', 'laypage'], function () {
            var element = layui.element;
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var laypage = layui.laypage;

            //出生日期
            laydate.render({
                elem: '#bday'
            });

            getDrugList(drugId,form);
            //用法用量点击
            $(document).on('click','#drugList .js-list-dosage',function(){
                var box91 = $(this).siblings('.js-dosageBox');
                if(box91.css('display') == 'none'){
                    $(".js-dosageBox").hide();
                    box91.show();
                    $(".js-remarkBox").hide();
                }else{
                    box91.hide();
                }
            });
            //备注点击
            $(document).on('click','#drugList .js-list-remark',function(){
                var box101 = $(this).siblings('.js-remarkBox');
                if(box101.css('display') == 'none'){
                    $(".js-remarkBox").hide();
                    $(".js-dosageBox").hide();
                    box101.show();

                }else{
                    box101.hide();
                }
            });
            //修改按钮点击
            $("#btnEdit").click(function(){
                $(".editBox").show();
                $(this).hide();
                changeToEdit(form,laydate);
            });
            //取消按钮点击
            $("#btnCancel").click(function(){
                parent.layui.layer.close(pageIndex);
            });

            // v1.1 信息校验
            form.verify({
                drug_name: function(value){
                    if(value == 0){
                        return '请选择药品';
                    }
                },
                drug_dose: function(value){
                    if(!new RegExp("(^$)|^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$").test(value)){
                        return '剂量只能输入正数';
                    }
                    if(parseInt(value) >= 100000){
                        return '最多只能输入5位数字';
                    }
                },
                other_mock: function(value){
                    if(value.length == 0 && $('input[name=other_dose]').val().length > 0){
                        return '请填写时间';
                    }
                    if(value.length > 5){
                        return '只能输入5个字';
                    }
                },
                other_dose: function(value){
                    if(value.length == 0 && $('input[name=other_mock]').val().length > 0){
                        return '请填写剂量';
                    }
                    if(!new RegExp("(^$)|^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$").test(value)){
                        return '剂量只能输入正数';
                    }
                    if(parseInt(value) >= 100000){
                        return '最多只能输入5位数字';
                    }
                },
                date_start: function(value){
                    if(value.length == 0){
                        return '请输入开始日期';
                    }
                },
                date_end: function(value){
                    var is_unused =  $("#drug_used").prop("checked");
                    if( is_unused == true && value.length == 0){
                        return '请输入结束日期';
                    }
                },
                remark_text: function(value){
                    if(value.length > 50){
                        return '输入内容不能超过50个字';
                    }
                },
            });

            //提交按钮点击
            var index2= 1;
            $("#btnSubmit").click(function(){
                console.log('do submit');
                params = {
                    '_method':'PUT',
                    'user_id': getLocalStorage('patient_id'),
                    'op_id':getLocalStorage('doc_id'),
                    'records':[]
                };

                var records = [];
                console.log(postRecords);
                //1. 遍历所有的行
                var errMsg = '';
                $("#drugList tr").each(function(index,item){
                    var id = $(this).attr('data-id');
                    //开始时间
                    if(postRecords[id]['start_date'] != '0001-01-01'){
                        postRecords[id]['start_date'] = $(this).find('.startDate').val();
                    }
                    //结束日期
                    if(postRecords[id]['end_date'] != '0001-01-01'){
                        postRecords[id]['end_date'] = $(this).find('.endDate').val();
                    }
                    //调整日期
                    if(postRecords[id]['adjust_date'] != '0001-01-01' || postRecords[id]['adjust_date'] != ''){
                        postRecords[id]['adjust_date'] = $(this).find('.adjustDate').val();
                    }
                    //单位
                    postRecords[id]['unit'] = $(this).find('select').val();
                    //判断总浏览和各济量值是否相等
                    valTotal = $(this).find('.js-dose').val();
                    if(valTotal == '') valTotal = 0;
                    val1 = $(this).find('.js-dosage1').val();
                    val2 = $(this).find('.js-dosage2').val();
                    val3 = $(this).find('.js-dosage3').val();
                    val4 = $(this).find('.js-dosage4').val();
                    val5 = $(this).find('.js-dosage5').val();
                    val6 = $(this).find('.js-dosage6').val();
                    if(val1 == '') val1 = 0;
                    if(val2 == '') val2 = 0;
                    if(val3 == '') val3 = 0;
                    if(val4 == '') val4 = 0;
                    if(val5 == '') val5 = 0;
                    if(val6 == '') val6 = 0;



                    if(parseFloat(valTotal) != parseFloat(val1) + parseFloat(val2) + parseFloat(val3) + parseFloat(val4) + parseFloat(val6)){
                        errMsg = '第'+ index2 + '行，总济量与用法用量的和不相等';
                    }

                    // //v1.1 检查输入剂量必须正数
                    // if(valTotal < 0 || val1 < 0 || val2 < 0 || val3 < 0 || val4 < 0 || val6 < 0 ){
                    //     layer.msg('药品剂量只能填写正数');
                    // }
                    // // v1.1 其他字段必须一起填
                    // if((val5 == 0) != (val6 == 0)){
                    //     layer.msg('其他用量的时间段和剂量必须一起填写');
                    // }
                    //
                    // if(valTotal != 0){
                    //     if((val1 != 0 || val2 != 0 || val3 != 0 || val4 != 0 || val6 != 0 ) && valTotal != (val1+val2+val3+val4+val6)){
                    //         layer.msg('总剂量和用法用量的和不相等');
                    //     }
                    // }else{
                    //     valTotal = val1+val2+val3+val4+val6;
                    //     if(valTotal == 0){
                    //         layer.msg('请输入剂量');
                    //     }
                    //     // params.drug_dose = valTotal;
                    // }

                    //每日济量
                    postRecords[id]['drug_dose'] = valTotal;
                    //用量
                    postRecords[id]['usage_dosage_morning'] = $(this).find('.js-dosage1').val(); //早
                    postRecords[id]['usage_dosage_noon'] = $(this).find('.js-dosage2').val(); //中
                    postRecords[id]['usage_dosage_night'] = $(this).find('.js-dosage3').val(); //晚
                    postRecords[id]['usage_dosage_bedtime'] = $(this).find('.js-dosage4').val(); //睡前
                    postRecords[id]['usage_dosage_other'] = {
                        'text':$(this).find('.js-dosage5').val(),
                        'dose':$(this).find('.js-dosage6').val()
                    }

                    //备注
                    postRecords[id]['remark'] = $(this).find('.js-remark').val();
                    index2++;
                });
                if(errMsg != ''){
                    layer.msg(errMsg);
                    return false;
                }
                var tmp = [];
                var index1 = 0;
                $.each(postRecords,function(index,item){
                    item['line'] = index1+1;
                    tmp.push(item);
                    index1 ++;
                })
                console.log(tmp);
                params.records = tmp;

                ajax_post2(configUrl.host + '/api/v1/pituitary/drug_edit',params,function(res){
                    if(res.status == 0){
                        window.location.reload();
                    }else{
                        layer.msg(res.msg);
                    }
                });
            });

        })
    })
</script>
</html>